package com.letv.whatslive.mongo.dao;

import com.google.common.collect.Lists;
import com.letv.whatslive.common.utils.ObjectUtils;
import com.letv.whatslive.model.CP;
import com.letv.whatslive.model.DeviceAllows;
import com.letv.whatslive.model.convert.CPConvert;
import com.letv.whatslive.model.convert.DeviceAllowsConvert;
import com.letv.whatslive.model.utils.ObjUtils;
import com.letv.whatslive.mongo.BaseDAO;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.WriteResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

//2015.11.4
/**
 * 设备白名单操作DAO
 * Created by shenyue on 2015/11/4.
 */
@Repository
public class DeviceAllowsDAO extends BaseDAO {
    protected String collectionName = "deviceAllows";

    private static final Logger logger = LoggerFactory.getLogger(DeviceAllowsDAO.class);

    @Override
    protected void init() {
        super.init(this.collectionName);
    }

    @Override
    protected long getAutoIncrementId() {
        return idGenerate.generateId(this.collectionName);
    }

    public Long saveOrUpdate(DeviceAllows deviceAllows) {
        DBObject query = new BasicDBObject("_id", deviceAllows.getId());
        DBObject dbo = this.dbCollection.findOne(query);
        if (dbo == null) {
            if(deviceAllows.getId()==null)
                deviceAllows.setId(getAutoIncrementId());
            dbo = DeviceAllowsConvert.castDeviceAllowsToDBObject(deviceAllows);
            if (dbo != null) {
                this.dbCollection.save(dbo);
                return ObjUtils.toLong(dbo.get("_id"));
            }
        } else {
            DBObject update = new BasicDBObject();

            if(StringUtils.isNotBlank(deviceAllows.getModel())){
                update.put("model",deviceAllows.getModel());
            }

            if(StringUtils.isNotBlank(deviceAllows.getSysVer())){
                update.put("sysVer",deviceAllows.getSysVer());
            }
            this.dbCollection.update(query, new BasicDBObject("$set", update), false, false);
            return deviceAllows.getId();
        }

        return 0L;
    }

    /**
     * 根据查询条件查询所有的设备列表
     * @param params
     * @param start
     * @param limit
     * @return
     */
    public List<DeviceAllows> getDeviceAllowsListByParams(Map<String, Object> params, Integer start, Integer limit) {
        List<DeviceAllows> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            Integer skip = start == null ? 0 : start;
            DBCursor cur = this.dbCollection.find(query).skip(skip).limit(limit);//按照视频类型和创建时间倒序
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                DeviceAllows deviceAllows = DeviceAllowsConvert.castDBObjectToDeviceAllows(dbObject);
                result.add(deviceAllows);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 根据查询条件Map获取查询条件对象
     * @param params
     * @return
     */
    private BasicDBObject getBasicDBObjectByParams(Map params){
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = new BasicDBObject();// 新建查询基类对象 dbo
        if (params != null && params.size() > 0) {
            if (params.get("_id") != null) {
                query.put("_id", ObjectUtils.toLong(params.get("_id")));
            }
            if (params.get("model") != null) {
                query.put("model", ObjectUtils.toString(params.get("model")));
            }
            if (params.get("sysVer") != null) {
                query.put("sysVer", ObjectUtils.toString(params.get("sysVer")));
            }
        }

        return query;
    }


    /**
     * 根据条件获取相应的设备列表
     * @param params
     * @return
     */
    public List<DeviceAllows> getAllDeviceAllowsByParams(Map<String, Object> params){
        List<DeviceAllows> result = Lists.newArrayList();
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            DBCursor cur = this.dbCollection.find(query);
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                DeviceAllows deviceAllows = DeviceAllowsConvert.castDBObjectToDeviceAllows(dbObject);
                result.add(deviceAllows);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 根据设备Id获取设备
     * @param deviceId
     * @return
     */
    public DeviceAllows getDeviceAllowsById(Long deviceId) {
        BasicDBObject query = new BasicDBObject();
        DeviceAllows deviceAllows = new DeviceAllows();
        query.put("_id", deviceId);
        DBObject dbObject = this.dbCollection.findOne(query);
        if (dbObject == null) return null;
        try {
            deviceAllows = DeviceAllowsConvert.castDBObjectToDeviceAllows(dbObject);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return deviceAllows;
    }

    public DeviceAllows saveDeviceAllows(DeviceAllows deviceAllows) {
        try {
            deviceAllows.setId(getAutoIncrementId());
            DBObject dbo = DeviceAllowsConvert.castDeviceAllowsToDBObject(deviceAllows);
            WriteResult wr = this.dbCollection.insert(dbo);
            return deviceAllows;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }
}